package com.thd.springboottest.shironostate.filter;

import com.thd.springboottest.shironostate.token.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * com.thd.springboottest.shiro.filter.MyFilter
 *
 * @author: wanglei62
 * @DATE: 2020/4/26 8:51
 **/
//public class MyFilter extends AccessControlFilter {
public class MyJwtFilter extends FormAuthenticationFilter {

    public MyJwtFilter() {
        super();
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        System.out.println(" MyJwtFilter isAccessAllowed ...");
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)throws Exception{
        System.out.println(" MyJwtFilter onAccessDenied ...");
        String headerToken= WebUtils.toHttp(request).getHeader("token");
        System.out.println("headerToken:" + headerToken);
        if(null == headerToken){
            response.getWriter().write("error! header token not exist");
            return false;
        }else{
            JwtToken tk = new JwtToken(headerToken);
            try{
                SecurityUtils.getSubject().login(tk);
                return true;
            }catch(Exception e ) {
                e.printStackTrace();
                response.getWriter().write(e.getMessage());
                return false;
            }
        }
    }
}
